<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/2
 * Time: 10:05
 */
namespace WebApp\lib\co\core;

use Generator;

/**
 * Class Task
 * @package WebApp\lib\co\core
 */
class Task
{
    public $task_id;
    public $pid;
    protected $coroutine;
    protected $send_value = null;
    protected $before_first_yield = true;

    /**
     * Task constructor.
     * @param $taskId
     * @param Generator $coroutine
     * @param $pid
     */
    public function __construct($taskId, Generator $coroutine, $pid)
    {
        $this->task_id = $taskId;
        $this->pid = $pid;
        $this->coroutine = $coroutine;
    }

    /**
     * @param $send_value
     */
    public function setSendValue($send_value)
    {
        $this->send_value = $send_value;
    }

    /**
     * @return mixed
     */
    public function run()
    {
        if ($this->before_first_yield) {
            $this->before_first_yield = false;
            return $this->coroutine->current();
        } else {
            $retval = $this->coroutine->send($this->send_value);
            $this->send_value = null;
            return $retval;
        }
    }

    /**
     * @return bool
     */
    public function isFinished()
    {
        return !$this->coroutine->valid();
    }
}
